import axios, { AxiosRequestConfig } from 'axios'
import store from '@/store'
import router from '@/router'

const request = axios.create()

request.interceptors.request.use(config => {
  const user = store.state.user
  if (user && user.token) {
    config.headers.Authorization = `Bearer ${user.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 控制登录过期的锁
let isRefreshing = false
request.interceptors.response.use(response => {
  const status = response.data.status
  // json数据及blob数据
  if (!status || status === 200) {
    return response
  }
  // 统一处理登录过期
  if (status === 410000) {
    if (isRefreshing) return Promise.reject(response)
    isRefreshing = true
    store.commit('setUser', null)
    // 跳转到登录页面
    router.push({
      name: 'login',
      query: {
        redirect: router.currentRoute.value.fullPath
      }
    })
    isRefreshing = false

    // 在内部消化掉这个业务异常
    return Promise.reject(response)
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then(res => {
    // 兼容blob数据
    return (res.data.data || res.data) as T
  })
}
